<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import request from "@/utils/request.js"  // 修改导入方式以使用请求实例
import { User, Lock, Message , EditPen} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";

const router = useRouter()
const role = ref('USER') // 默认选择普通用户

// 修改角色选项为注册页专用
const roleOptions = {
    USER: "普通用户",
    RIDER: "配送骑手",
};

// 修改表单数据结构
const formData = ref({
    nickname:'',
    username: '',
    password: '',
    confirmPassword: '',
    email: '',
    role: 'USER'
})

// 扩展验证规则
const rules = ref({
    nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
        { min: 1, max: 16, message: '长度在 1 到 16 个字符', trigger: 'blur' }
    ],
    username: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== formData.value.password) {
                    callback(new Error('两次输入密码不一致'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    role: [
        { required: true, message: '请选择角色', trigger: 'change' }  
    ]
})

// 修改处理函数为注册逻辑
const handleRegister = async () => {
    try {
        await formRef.value.validate()

        const data = await request.post('/register', {
            nickname: formData.value.nickname,
            username: formData.value.username,
            password: formData.value.password,
            role: role.value,
            email: formData.value.email
        })

        if (data.code === 200) {
            ElMessage.success('注册成功')
            router.push('/login') // 跳转登录页
        }
    } catch (error) {
        ElMessage.error(`注册失败`)
        console.log(`注册失败: ${error}`)
    }
}

// 获取表单引用
const formRef = ref(null)

const handleLogin = async () => {
    try {
        await formRef.value.validate()
        // 新增登录逻辑
        const data = await request.post('/login', {
            username: formData.value.account, // 映射账号字段
            password: formData.value.password,
            role: role.value
        })

        if (data.code === 200) {
            ElMessage.success('登录成功')
            localStorage.setItem('user', JSON.stringify(data.data))
            // console.log(data);
            // router.push('/')
        } else {
            ElMessage.error(data.message || '登录失败')
            // console.log(data)
        }
    } catch (error) {
        // 错误处理
        const errorMsg = error.response?.data?.message || error.message
        ElMessage.error(`登录失败: ${errorMsg}`)
        console.error('登录请求失败:', error)
    }
}
</script>


<template>
    <div class="container">
        <el-card class="login-card">
            <div slot="header" class="card-header">
                <el-link
                    :underline="false"
                    @click="router.push('/')"
                    class="home-link"
                >
                  &lt; 返回主页
                </el-link>
                <span class="welcome-text">注册新账号</span>
            </div>
            <el-form ref="formRef" :model="formData" :rules="rules" @submit.prevent>

                <el-form-item prop="nickname">
                  <el-input :prefix-icon="EditPen" v-model="formData.nickname" placeholder="请输入昵称" />
                </el-form-item>

                <el-form-item prop="username">
                    <el-input :prefix-icon="User" v-model="formData.username" placeholder="请输入账号" />
                </el-form-item>

                <el-form-item prop="password">
                    <el-input :prefix-icon="Lock" v-model="formData.password" type="password" placeholder="请输入密码"
                        show-password />
                </el-form-item>

                <el-form-item prop="confirmPassword">
                    <el-input :prefix-icon="Lock" type="password" v-model="formData.confirmPassword"
                        placeholder="请确认密码" />
                </el-form-item>

                <el-form-item prop="email">
                    <el-input :prefix-icon="Message" v-model="formData.email" placeholder="请输入邮箱"/>
                </el-form-item>

                <el-form-item label="身份" class="role-form-item">
                    <el-select v-model="role" placeholder="请选择角色" class="role-select">
                        <el-option v-for="(label, value) in roleOptions" :key="value" :label="label" :value="value" />
                    </el-select>
                </el-form-item>

                <div class="button-group">
                    <el-button type="primary" @click="handleRegister" class="register-btn">立即注册</el-button>
                    <el-link :underline="false" @click="router.push('/login')">
                        已有账号？立即登录
                    </el-link>
                </div>
            </el-form>
        </el-card>
    </div>
</template>

<style scoped>
/* 调整角色选择器样式 */
:deep(.el-select.role-select) {
    --el-font-size-base: 16px;
    width: 100%;
}

:deep(.el-select.role-select .el-input__inner) {
    height: 40px;
    line-height: 40px;
    font-size: var(--el-font-size-base);
}

:deep(.el-select.role-select .el-select__caret) {
    font-size: var(--el-font-size-base);
}

:deep(.el-select-dropdown__item) {
    font-size: var(--el-font-size-base);
    padding: 8px 32px;
}

.container {
    background-image: url("@/assets/bg.png");
    width: 100%;
    height: 100vh;
    background-size: cover;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
}

.login-card {
  padding-top: 20px;
  width: 450px;
}

.card-header {
  position: relative;
  text-align: center;
  margin-bottom: 25px;
}

.home-link {
  position: absolute;
  left: 5px;
  top: 0;
  transform: translateY(-50%);
  font-size: 14px;
  color: var(--el-color-primary);
}

.welcome-text {
    font-size: 24px;
    font-weight: 600;
}

:deep(.el-form-item__label) {
    font-size: 16px;
}

:deep(.el-input__inner) {
    font-size: 16px;
    height: 40px;
}

.button-group {
    margin-top: 25px;
    display: flex;
    flex-direction: column;
    gap: 15px;
}

:deep(.login-btn) {
    width: 100%;
    height: 45px;
    font-size: 16px;
}

:deep(.register-link) {
    width: 100%;
    color: var(--el-color-primary);
    text-align: center;
    padding: 10px 0;
}

/* 调整输入框容器宽度 */
:deep(.role-form-item .el-form-item__content) {
    flex: 1;
    min-width: 0;
    /* 防止内容溢出 */
}
</style>